using BuildingBlocks.Infrastructure.EventBus;
using Identity.Application.Contracts.Common;
using Identity.Application.Contracts.Events;
using Identity.Application.Contracts.Services;
using Identity.Application.Users.Commands;
using MediatR;

namespace Identity.Application.Users.CommandHandler;

public class SendCodeEmailWithResetPasswordCommandHandler : IRequestHandler<SendCodeEmailWithResetPasswordCommand, Result>
{
    private readonly IUserService _userService;
    private readonly IRedisService _redisService;
    private readonly IEventBus _eventBus;


    public SendCodeEmailWithResetPasswordCommandHandler(IUserService userService, IRedisService redisService, IEventBus eventBus)
    {
        _userService = userService;
        _redisService = redisService;
        _eventBus = eventBus;
    }
    public async Task<Result> Handle(SendCodeEmailWithResetPasswordCommand request, CancellationToken cancellationToken)
    {

        var resetToken = await _userService.GeneratePasswordResetTokenAsync(request.email);
        var code = GenerateCustomCode();

        // 存 Redis，设置过期时间，比如15分钟
        await _redisService.SetStringAsync($"reset_code:{code}", resetToken, TimeSpan.FromMinutes(15));
        var sendEmailEvent = new SendCodeEmailWithResetPasswordEvent(request.email, code);
        await _eventBus.PublishAsync(sendEmailEvent);

        return Result.Success("验证码已经发送至邮箱！");
    }

    public string GenerateCustomCode()
    {
        var length = 6;
        var random = new Random();
        var code = "";
        for (int i = 0; i < length; i++)
        {
            code += random.Next(0, 10).ToString();
        }
        return code;
    }
}